package com.spit.fammo.ui.frg

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.spit.amoeba.base.BaseFragment
import com.spit.fammo.R
import com.spit.fammo.databinding.FDownloadBinding
import com.spit.fammo.ext.showMessage
import com.spit.fammo.viewmodel.DownloadModel
import com.spit.fammo.viewmodel.RfidModel
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.appContext
import java.text.NumberFormat
import java.util.concurrent.TimeUnit

/**
 * User: Nike
 *  2025/1/6 16:48
 *      下载
 */
class DownloadFrg : BaseFragment<DownloadModel, FDownloadBinding>() {

    val numberFormat = NumberFormat.getInstance()

    var stockNumber: Int = 0
    var stockAllSize: Int = 0
    var stockDisposable: Disposable? = null

    val rfidModel: RfidModel by activityViewModels()

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel
        numberFormat.setMaximumFractionDigits(2)

        //盘点
        mDatabind.pvStock.setOnProgressChangeListener{
            mDatabind.pvStock.labelText = "$stockNumber" + "/" + "$stockAllSize" + " " + "${it.toInt()}%"
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                stockDisposable?.dispose()
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                stockDisposable?.dispose()
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                setToolBarTitle(getString(R.string.download))
                if (!NetworkUtils.isConnected()){
                    showMessage(appContext.getString(R.string.no_internet))
                    return
                }
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    mViewModel.stockTakeListDao.deleteAll()
                    mViewModel.assetDao.deleteAll()
                    mViewModel.uploadOrderDao.deleteAll()
                    mViewModel.uploadOrderListDao.deleteAll()
                    withContext(Dispatchers.Main) {
                        rfidModel.mainDrawerUploadNum.value = 0
                        mDatabind.pvStock.progress = 0f
                        mViewModel.onStock()
                    }
                }
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listStockTakeBean.observe(viewLifecycleOwner, Observer {
            mViewModel.stockTakename.set(if (it.total != 0) appContext.getString(R.string.stock_take) else appContext.getString(R.string.stock_take) + "(" + appContext.getString(R.string.no_data) + ")")
            if (it.total != 0){
                stockAllSize = it.total
                mViewModel.viewModelScope.launch {
                    mViewModel.assetDao.findAll(mViewModel.userId!!)
                        .flowOn(Dispatchers.IO)
                        .collect { data ->
                            stockNumber = data.size
                        }
                }
                stockDisposable = Observable.interval(1, TimeUnit.SECONDS)
                    .observeOn(Schedulers.io()) // 切换到IO线程执行操作
                    .subscribe ({ tick ->
                        var result = numberFormat.format(stockNumber.toFloat() / stockAllSize.toFloat() * 100).toFloat()
                        mDatabind.pvStock.progress = result
                        if (stockNumber >= it.total){
                            stockDisposable?.dispose()
                        }
                    }, { error ->
                        LogUtils.e(error)
                    })
            }
        })
    }

}